package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.Const;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.service.HTicketSellOrderService;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgDeptMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.utils.FleaStringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @program: project
 * @description: 组团社门票销售记录
 * @author: shiliqiang
 * @create: 2018-12-31 10:30
 * @version: 1.0
 */
@Service
public class HTicketSellOrderServiceImpl implements HTicketSellOrderService {

    @Autowired
    private HTicketSellOrderMapper hTicketSellOrderMapper;
    @Autowired
    private HTicketSellOrderItemMapper hTicketSellOrderItemMapper;
    @Autowired
    private HTicketSellPayInfoMapper hTicketSellPayInfoMapper;
    @Autowired
    private SpotTicketMapper spotTicketMapper;
    @Autowired
    private OrgDeptMapper orgDeptMapper;
    @Autowired
    private HSpotMapper hSpotMapper;

    @Override
    public ServerResponse<Map<String, Object>> selectSellOrderItemInfo(String orderId) {
        List<HTicketSellOrderItem> items = hTicketSellOrderItemMapper.selectByOrderId(orderId);
        if (CollectionUtils.isNotEmpty(items)){
            for (HTicketSellOrderItem item :items){
                String ticketType = item.getTicketTypeName();
                if (StringUtils.isNotEmpty(item.getTicketTypeName()))
                    item.setTicketTypeName(getType(ticketType));
            }
        }
        //取得支付信息
        HTicketSellPayInfo sellPayInfo = hTicketSellPayInfoMapper.selectByOrderId(orderId);
        Map<String,Object> dataMap = Maps.newHashMap();
        dataMap.put("sellPayInfo",sellPayInfo);
        dataMap.put("sellItems",items);
        return ServerResponse.createBySuccess(dataMap);
    }

    @Override
    public ServerResponse<FleaPage<HTicketSellOrder>> selectSellOrderInfo(int curPage, int pageSize, String deptUuid,String spotName) {
        List<HSpot> spots=null;

        if (!spotName.equals("")){
            StringBuilder sb = new StringBuilder();
            sb.append("%");
            sb.append(spotName);
            sb.append("%");
            spotName = String.valueOf(sb);
            spots = hSpotMapper.selectByName(spotName);
            if (CollectionUtils.isEmpty(spots)){
                return ServerResponse.createBySuccess(new FleaPage<HTicketSellOrder>());
            }
        }
        RowBounds rowBounds = new RowBounds(curPage,pageSize);
        List<HTicketSellOrder> orders = hTicketSellOrderMapper.selectByDeptId(deptUuid,rowBounds,spots);
        FleaPage<HTicketSellOrder> orderFleaPage = new FleaPage<>(orders);
        List<HTicketSellOrder> newList = Lists.newArrayList();
        for (HTicketSellOrder order : orders) {
            OrgDept dept = orgDeptMapper.selectByPrimaryKey(order.getgDeptId());
            if (dept==null){
                continue;
            }
            order.setgDeptName(dept.getDeptName());
            newList.add(order);
        }
        orderFleaPage.setCurPage(curPage);
        orderFleaPage.setPageSize(pageSize);
        orderFleaPage.setCurPageData(newList);
        FleaPage<HTicketSellOrder> itemFleaPage = new FleaPage<>(orders);
        return ServerResponse.createBySuccess(itemFleaPage);
    }

    @Override
    public ServerResponse<String> saveSellOrder(String model, String userId, String deptUuid) throws Exception {
        JSONObject jsonObject = JSONObject.parseObject(model);
        List<HTicketSellOrderItem> sellItems = JSON.parseArray(jsonObject.getString("item"), HTicketSellOrderItem.class);
        HTicketSellPayInfo sellPayInfo = JSON.parseObject(jsonObject.getString("payinfo"), HTicketSellPayInfo.class);
        HTicketSellOrder order = new HTicketSellOrder();
        float totalAmount=0;
        int totalTicketNum = 0;
        //支付信息

        //创建订单
        String orderId = FleaStringUtils.getGenerateUUID();
        order.setId(orderId);
        order.setCreateUser(userId);
        order.setzDeptId(deptUuid);
        //获取订单项
        String gDeptId;
        //为了取得供应商id；
        String ticketId1 = sellItems.get(0).getTicketId();
        SpotTicket ticketEntity1 = spotTicketMapper.selectByPrimaryKey(ticketId1);
        if (ticketEntity1==null){
            return ServerResponse.createByErrorMessage("组团社门票不存在");
        }
        String spotId = ticketEntity1.getUuid();
        if (StringUtils.isBlank(spotId)){
            return ServerResponse.createByErrorMessage("景点ID为空");
        }
        HSpot hSpot = hSpotMapper.selectByPrimaryKey(spotId);
        if (null == hSpot){
            return ServerResponse.createByErrorMessage("供应商景点不存在");
        }
        gDeptId = hSpot.getUuid();
        List<HTicketSellOrderItem> newItems = Lists.newArrayList();
        for (HTicketSellOrderItem item : sellItems){
            item.setCreateUser(userId);
            item.setTicketSellOrderId(orderId);

            //判断库存
            String ticketId = item.getTicketId();
            if (StringUtils.isEmpty(ticketId)){
                return ServerResponse.createByErrorMessage("门票ID不能为空");
            }
            SpotTicket ticketEntity = spotTicketMapper.selectByPrimaryKey(ticketId);
            if (ticketEntity==null){
                return ServerResponse.createByErrorMessage("门票不存在");
            }



            Integer stock = ticketEntity.getNumber();

            Integer ticketNum = item.getTicketNum();
            if (ticketNum==null || ticketNum==0){
                continue;
            }
            if (stock==null || ticketNum>stock){
                String ticketType = ticketEntity.getType();
                return ServerResponse.createByErrorMessage(getType(ticketType)+"库存不足");
            }
            float currentPrice = ticketEntity.getSalePrice();
            //计算总价

            totalAmount += currentPrice*ticketNum;
            //计算总数量
            totalTicketNum += ticketNum;

            item.setTicketId(ticketId);
            item.setCurrentPrice(currentPrice);
            item.setTicketNum(ticketNum);
            item.setId(FleaStringUtils.getGenerateUUID());
            newItems.add(item);
        }
        //持久化订单
        order.setTotalAmount(totalAmount);
        order.setQuantity(totalTicketNum);
        order.setgDeptId(gDeptId);
        order.setSpotId(hSpot.getId());
        int row =  hTicketSellOrderMapper.insertSelective(order);
        if (row!=1){
            return ServerResponse.createByErrorMessage("创建订单失败");
        }

        row = hTicketSellOrderItemMapper.insertBatch(newItems);
        if (row!=newItems.size()){
            throw new Exception("批量创建游客门票订单项失败");
        }
        //更新库存
        for (HTicketSellOrderItem item :newItems){
            String ticketId = item.getTicketId();
            if (StringUtils.isEmpty(ticketId)){
                throw new Exception("门票ID不能为空");
            }
            SpotTicket ticketEntity = spotTicketMapper.selectByPrimaryKey(ticketId);
            if (ticketEntity==null){
                throw new Exception("门票不存在");
            }
            int stock = ticketEntity.getNumber();
            int ticketNum = item.getTicketNum();
            if (stock>=ticketNum){
                int updateStock = stock-ticketNum;
                ticketEntity.setNumber(updateStock);
                row = spotTicketMapper.updateByPrimaryKeySelective(ticketEntity);
                if (row!=1){
                    throw new Exception("更新门票库存失败");
                }
            }else{
                throw new Exception("库存不足");
            }
        }
        //添加支付信息
        sellPayInfo.setId(FleaStringUtils.getGenerateUUID());
        sellPayInfo.setCreateUser(userId);
        sellPayInfo.setPayMoney(totalAmount);
        sellPayInfo.setTicketDeptOrderId(orderId);
        row = hTicketSellPayInfoMapper.insertSelective(sellPayInfo);
        if (row!=1){
            throw new Exception("添加支付信息失败");
        }
        return ServerResponse.createBySuccessMessage("游客门票下单成功");
    }
    public static String getType(String ticketType){
        switch (ticketType){
            case HConstant.D_SPOT_TICKET_TYPE_OTHER :
                ticketType = Const.SpotTicketTypeEnum.OTHER.getValue();
                return ticketType;
            case HConstant.D_SPOT_TICKET_TYPE_OLD :
                ticketType = Const.SpotTicketTypeEnum.OLD.getValue();
                return ticketType;
            case HConstant.D_SPOT_TICKET_TYPE_STU :
                ticketType = Const.SpotTicketTypeEnum.STUDENT.getValue();
                return ticketType;
            case HConstant.D_SPOT_TICKET_TYPE_ADULT :
                ticketType = Const.SpotTicketTypeEnum.ADULT.getValue();
                return ticketType;
            case HConstant.D_SPOT_TICKET_TYPE_CHILDREN :
                ticketType = Const.SpotTicketTypeEnum.CHILDREN.getValue();
                return ticketType;
        }
        return "";
    }
}
